package cn.changhong.user.config;

import cn.changhong.user.filter.JWTAuthenticationFilter;

import cn.changhong.user.filter.JWTLoginFilter;
import cn.changhong.user.util.UserDetailsServiceImpl;
import cn.changhong.user.util.CustomAuthenticationProvider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author zz
 * @Date
 **/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new CustomAuthenticationProvider(userDetailsService));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers("/user_manage/user/register","/user_manage/user/commonUser/forgetPassword").permitAll()
                .antMatchers("/user_manage/*/commonUser/*").hasAnyRole("CommonUser","Admin","SuperAdmin")
                .antMatchers("/user_manage/*/admin/*").hasAnyRole("Admin","SuperAdmin")
                .antMatchers("/user_manage/*/superAdmin/*").hasRole("SuperAdmin")
                .and()
                .addFilterBefore(new JWTLoginFilter("/user_manage/user/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new JWTAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
    }
}

